﻿using System;
using System.Collections.Generic;

namespace Basmus.Conel
{
    public class StringCollectionBinder : IBinder
    {
        public Binding Bind(Type containerType)
        {
            if (containerType.IsArray && containerType.GetElementType() == typeof(string))
            {
                return new StringArrayBinding();
            }

            if (containerType.IsGenericType && !containerType.IsGenericTypeDefinition)
            {
                if (containerType.GetGenericArguments()[0] == typeof(string))
                {
                    var genericTypeDefinition = containerType.GetGenericTypeDefinition();
                    
                    if (genericTypeDefinition == typeof (IEnumerable<>))
                    {
                        return new StringArrayBinding();
                    }

                    if (genericTypeDefinition == typeof (List<>) || genericTypeDefinition == typeof (IList<>))
                    {
                        return new StringListBinding();
                    }
                }
            }

            return null;
        }

        public Binding Bind(Type containerType, Type elementType)
        {
            if (elementType == typeof(string))
            {
                if (containerType.IsArray && elementType == containerType.GetElementType())
                {
                    return new StringArrayBinding();
                }

                if (containerType.IsGenericType && !containerType.IsGenericTypeDefinition)
                {
                    if (elementType == containerType.GetGenericArguments()[0])
                    {
                        var genericTypeDefinition = containerType.GetGenericTypeDefinition();

                        if (genericTypeDefinition == typeof (IEnumerable<>))
                        {
                            if (elementType == containerType.GetGenericArguments()[0])
                            {
                                return new StringArrayBinding();
                            }
                        }

                        if (genericTypeDefinition == typeof (List<>) || genericTypeDefinition == typeof (IList<>))
                        {
                            if (elementType == containerType.GetGenericArguments()[0])
                            {
                                return new StringListBinding();
                            }
                        }
                    }
                }
            }
            return null;
        }
    }
}